package com.sniper.springmvc.utils;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by suzhen on 2017/4/12.
 */
public abstract class ExeclBaseUtil {
    protected final static Logger LOGGER = LoggerFactory.getLogger(ExeclJyzxExportUtil.class);
    protected Workbook workbook = null;
    /**
     * 文件根目录
     */
    protected String rootDir;
    protected Font font;
    /**
     * 导入的数据行数
     */
    protected int importCount = 0;
    /**
     * 储存循环读取数据的字段
     */
    protected Map<String, String> valueMapFields = new LinkedHashMap<>();
    /**
     * 包含顶部显示文字和每一行的数据读取字段名称
     */
    protected List<Map<String, String>> headFields = new ArrayList<>();


    public void setRootDir(String rootDir) {
        this.rootDir = rootDir;
    }

    
    public void setValueMapFields(Map<String, String> valueMapFields) {
        this.valueMapFields = valueMapFields;
        this.headFields.add(valueMapFields);
    }

    public List<Map<String, String>> getHeadFields() {
        return headFields;
    }

    public void setFont(Font font) {
        this.font = font;
    }

    /**
     * 数据输出起始行
     */
    protected int headStart = 0;

    public double getResult(float a) {
        BigDecimal bigDecimal = new BigDecimal(a);
        BigDecimal b = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        return b.floatValue() * 100;
    }

    public double getResult(double a) {
        BigDecimal bigDecimal = new BigDecimal(a);
        BigDecimal b = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
        return b.doubleValue() * 100;
    }


    /**
     * 表达式查找字符串是否存在
     *
     * @param str
     * @param reg
     * @return
     */
    public boolean findString(String str, String reg) {
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }

    private int getMapDate(Object a) {
        int result = 0;
        if (!ValidateUtil.isValid(a)) {
            return result;
        }
        if (a.getClass() == BigDecimal.class) {
            BigDecimal bigDecimal = (BigDecimal) a;
            result = bigDecimal.intValue();
        } else if (a.getClass() == Long.class) {
            long view = (long) a;
            result = Long.valueOf(view).intValue();
        } else {
            int view = (int) a;
            result = Integer.valueOf(view).intValue();
        }
        return result;
    }

    /**
     * 设置导出的头部
     *
     * @param sheet
     */
    public void setSheetHeader(Sheet sheet) {

        this.headStart = headFields.size();
        // 循环所有的
        int r = 0;
        for (Map<String, String> map : headFields) {
            int c = 0;
            Row row = sheet.createRow(r);
            // 循环标题
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (entry.getKey().startsWith(":")) {
                    String key = entry.getKey().substring(1);
                    String[] keys = key.split("-");
                    if (keys.length == 2) {
                        // 合并，如果是有一行数据表示合并一行
                        mergeCell(sheet, r, r, Integer.valueOf(keys[0]), Integer.valueOf(keys[1]));
                        createCell(row, Integer.valueOf(keys[0]), entry.getValue(), CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    } else if (keys.length == 4) {
                        // 合并，这里处室上下左右合并
                        // 顺序是左-右-上-下
                        mergeCell(sheet, r, Integer.valueOf(keys[0]), Integer.valueOf(keys[1]), Integer.valueOf(keys[2]));
                        createCell(row, Integer.valueOf(keys[0]), entry.getValue(), CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                    }

                } else {
                    createCell(row, c, entry.getValue(),
                            CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_CENTER);
                }
                c++;
            }
            r++;
        }
    }

    /**
     * 自定义设置莫一行的
     *
     * @param sheet
     * @param headers
     * @param rowCount
     */
    public void setSheetHeaderCustom(Sheet sheet, Map<String, String> headers,
                                     int rowCount) {
        short i = 0;
        Row row = sheet.createRow(rowCount);
        for (Map.Entry<String, String> entry : valueMapFields.entrySet()) {
            createCell(row, i, entry.getValue(), CellStyle.ALIGN_CENTER,
                    CellStyle.VERTICAL_CENTER);
            i++;
        }
    }

    /**
     * Creates a cell and aligns it a certain way.
     *
     * @param row    the row to create the cell in
     * @param column the column number to create the cell in
     * @param halign the horizontal alignment for the cell.
     */

    public void createCell(Row row, int column, String value, short halign, short valign) {
        Cell cell = row.createCell(column);
        if (ValidateUtil.isValid(value)) {
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            // int width = value.length() * 500;
            // Sheet sheet = row.getSheet();
            // sheet.setColumnWidth(column, width);
            cellStyle.setAlignment(halign);
            cellStyle.setVerticalAlignment(valign);

            cell.setCellStyle(cellStyle);
            cell.setCellValue(value);
        } else {
            cell.setCellValue("");
        }
    }

    public void createCell(Row row, int column, Object value, short halign, short valign) {
        if (value.getClass() == Integer.class) {
            int val = (int) value;
            createCell(row, column, val, halign, valign);
        } else if (value.getClass() == String.class) {
            String val = (String) value;
            createCell(row, column, val, halign, valign);
        } else if (value.getClass() == Long.class) {
            long val = (long) value;
            createCell(row, column, val, halign, valign);
        } else if (value.getClass() == Float.class) {
            float val = (float) value;
            createCell(row, column, val, halign, valign);
        } else if (value.getClass() == Double.class) {
            double val = (double) value;
            createCell(row, column, val, halign, valign);
        }
    }

    public void createCell(Row row, int column, Integer value, short halign, short valign) {
        Cell cell = row.createCell(column);
        if (ValidateUtil.isValid(value)) {
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            // int width = String.valueOf(value).length() * 250;
            // Sheet sheet = row.getSheet();
            // sheet.setColumnWidth(column, width);
            cellStyle.setAlignment(halign);
            cellStyle.setVerticalAlignment(valign);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(value);
        } else {
            cell.setCellValue(0);
        }

    }

    public void createCell(Row row, int column, long value, short halign, short valign) {
        Cell cell = row.createCell(column);
        if (ValidateUtil.isValid(value)) {
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            cellStyle.setAlignment(halign);
            cellStyle.setVerticalAlignment(valign);

            cell.setCellStyle(cellStyle);
            cell.setCellValue(value);
        } else {
            cell.setCellValue(0);
        }
    }

    public void createCell(Row row, int column, float value, short halign, short valign) {
        Cell cell = row.createCell(column);
        if (ValidateUtil.isValid(value)) {
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);
            // int width = String.valueOf(value).length() * 250;
            // Sheet sheet = row.getSheet();
            // sheet.setColumnWidth(column, width);
            cellStyle.setAlignment(halign);
            cellStyle.setVerticalAlignment(valign);

            cell.setCellStyle(cellStyle);
            cell.setCellValue(value);
        } else {
            cell.setCellValue(0);
        }

    }

    public void createCell(Row row, int column, double value, short halign, short valign) {
        Cell cell = row.createCell(column);
        if (ValidateUtil.isValid(value)) {
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);

            cellStyle.setAlignment(halign);
            cellStyle.setVerticalAlignment(valign);

            cell.setCellStyle(cellStyle);
            cell.setCellValue(value);

        } else {
            cell.setCellValue(0);
        }
    }

    public void createCell(Row row, int column, Date value, short halign, short valign) {
        Cell cell = row.createCell(column);
        if (ValidateUtil.isValid(value)) {
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setWrapText(true);

            cellStyle.setAlignment(halign);
            cellStyle.setVerticalAlignment(valign);

            cell.setCellStyle(cellStyle);

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            cell.setCellValue(dateFormat.format(value));
        } else {
            cell.setCellValue("");
        }
    }

    /**
     * 合并cell
     *
     * @param sheet
     * @param a     first row
     * @param b     last row
     * @param c     first column
     * @param d     last column
     */
    private void mergeCell(Sheet sheet, int a, int b, int c, int d) {
        sheet.addMergedRegion(new CellRangeAddress(a, b, c, d));
    }
}
